package com.eati.cm.auth;

import com.eati.cm.serv.ILoginServ;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.deser.BasicDeserializerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;


public class CmAuthFilter extends AbstractAuthenticationProcessingFilter {

    private AuthenticationManager authenticationManager;

    ILoginServ loginServ;

    public CmAuthFilter(AuthenticationManager authenticationManager, ILoginServ loginServ){
        super(new AntPathRequestMatcher("/User/Login/thirdPartyLoginCB/*", "GET"));
        this.authenticationManager = authenticationManager;
        this.loginServ = loginServ;
    }

    @Override
    public Authentication attemptAuthentication(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws AuthenticationException, IOException, ServletException {
    	System.out.println("CmAuthFilter::attemptAuthentication!!");
        
    	ThirdpartyAuthCBToken token = (ThirdpartyAuthCBToken) loginServ.getLoginDispByThirdPartyName(
    			loginServ.getThirdpartyLoginPlatformName(httpServletRequest)
    			).squeeze(httpServletRequest);
    	
    	System.out.println("thirdPartyName: " + token.thirdpartyAuthPlatformName
        		+ ", code: " + token.cbCode);
    	
        return this.authenticationManager.authenticate(token);

        //String authCode = httpServletRequest.getParameter("code");



        /*String usrId = httpServletRequest.getParameter("usrId");
        Authentication auth = this.authenticationManager.authenticate(
                new UserAuthToken(usrId)
        );
        if(auth != null){
            super.setContinueChainBeforeSuccessfulAuthentication(true);
        }
        return auth;*/
    }
}